SOURCE_ROOT=.
TARGET = simple-c
CROSS_COMPILE := riscv32-unknown-elf-
CC = $(CROSS_COMPILE)gcc
LD = $(CROSS_COMPILE)ld

BUILD_DIR = ./build
SRC_DIR = ./src
C_FILES = $(wildcard $(SRC_DIR)/*.c)
ASM_FILES = $(wildcard $(SRC_DIR)/*.S)
OBJ_FILES = $(C_FILES:$(SRC_DIR)/%.c=$(BUILD_DIR)/%_c.o)
OBJ_FILES += $(ASM_FILES:$(SRC_DIR)/%.S=$(BUILD_DIR)/%_s.o)

CFLAGS = -march=rv32i -mabi=ilp32 -fno-pic -Os -g -nostartfiles -Wl,--no-relax -Wl,--gc-sections
ASMFLAGS = -march=rv32i -mabi=ilp32
LDS = $(SRC_DIR)/default.ld
LDFLAGS = -T $(LDS)
TARGET_ELF = $(BUILD_DIR)/$(TARGET).elf

.PHONY: all clean

$(BUILD_DIR)/%_c.o: $(SRC_DIR)/%.c
	mkdir -p $(@D)
	$(CC) $(CFLAGS) -c $< -o $@

$(BUILD_DIR)/%_s.o: $(SRC_DIR)/%.S
	$(CC) $(ASMFLAGS) -c $< -o $@

all: $(OBJ_FILES)
	echo "make start"
	$(LD) $(LDFLAGS) -o $(TARGET_ELF) $(OBJ_FILES)
clean:
	rm -rf $(BUILD_DIR)
